package com.shop.server.service.impl;

import com.shop.common.constant.MessageConstant;
import com.shop.common.constant.RedisConstant;
import com.shop.common.entity.CommonResult;
import com.shop.common.pojo.User;
import com.shop.common.util.StrUtils;
import com.shop.server.mapper.UserMapper;
import com.shop.server.pojo.RegisterUser;
import com.shop.server.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.crypto.Data;
import java.util.Date;

/**
 * @author ghy
 * @version 1.0
 * @date 2020-10-29
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    BCryptPasswordEncoder bcryptPasswordEncoder;


    /**
     * 增加
     *
     * @param user
     * @return
     */
    @Override
    public CommonResult insert(User user) {
        //默认设置状态为未激活
        int status = 0;
        if(user instanceof RegisterUser) {
            RegisterUser u = (RegisterUser) user;
            CommonResult result = checkCode(u);
            if(!result.getIsSuccess()){
                return result;
            } else {
                //验证码是对的，那么状态是已激活
                status = 1;
            }
        }

        Date now = new Date();
        System.out.println(now);
        //密码加密
        String bcryptPwd = bcryptPasswordEncoder.encode(user.getPassword());
        user.setPassword(bcryptPwd);
        user.setCreateTime(now);
        user.setUpdateTime(now);
        user.setStatus(status);
        userMapper.insert(user);
        return new CommonResult<>(MessageConstant.REG_SUCCESS, "您可以使用手机号直接登录！");
    }

    /**
     * 判断验证码是否正确
     *
     * @param user
     * @return
     */
    @Override
    public CommonResult checkCode(RegisterUser user) {
        //1.获取手机号，从redis获取验证码
        String phone = user.getPhone();
        String codeKey = StrUtils.getRedisKey(RedisConstant.SHOP_REGISTER, phone);
        String redisCode = (String) redisTemplate.opsForValue().get(codeKey);
        //2.比对验证码
        //2.1 没对上=======================
        if(redisCode == null || redisCode.equalsIgnoreCase("")) {
            //验证码已过期
            return new CommonResult<>(false, MessageConstant.CODE_TIMEOUT, "请重新获取！");
        }
        if(!redisCode.equalsIgnoreCase(user.getCode())) {
            //验证码错误
            return new CommonResult<>(false, MessageConstant.CODE_ERROR, "请重新输入！");
        }
        //=======================
        return new CommonResult<>();
    }
}
